package cn.achao.csr.file.service.impl;

import cn.achao.csr.base.constant.enums.SysSourceEnum;
import cn.achao.csr.base.exception.BusinessException;
import cn.achao.csr.base.utils.ThrowUtils;
import cn.achao.csr.file.config.MinioConfig;
import cn.achao.csr.file.core.model.resp.MinIoFileResp;
import cn.achao.csr.file.service.UploadService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Author: achao
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class UploadServiceImpl implements UploadService {

    private final MinioConfig minioConfig;
    private final MinioClient minioClient;

    private final ThreadPoolTaskExecutor taskExecutor;

    @Override
    public MinIoFileResp upload(MultipartFile file) {
        MinIoFileResp resp = new MinIoFileResp();
        try {
            // 获取文件真实名称
            String originalFilename = file.getOriginalFilename();
            // 获取文件的扩展名 例如.jpg .doc
            String extname = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 构建文件上传相关信息
            PutObjectArgs args = PutObjectArgs.builder()
                    .bucket(minioConfig.getBucketName())
                    .object(originalFilename)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build();
            // 将文件上传到minio服务器
            minioClient.putObject(args);
            log.info("文件上传成功");
            // 组装文件信息，返回前端 或者存入数据路
            String url = minioConfig.getUrl() + "/" + minioConfig.getBucketName() + "/" + originalFilename;
            log.info("文件上传地址：{}", url);
            resp.setUrl(url);
            resp.setSize(file.getSize());
            resp.setFileName(originalFilename);
            resp.setExtname(extname);
            // TODO 异步存储文件信息到数据库
        } catch (Exception e) {
            log.error("文件上传失败", e);
            ThrowUtils.throwIf(BusinessException.fail("文件上传失败", SysSourceEnum.CSR_FILE.getSysName()));
        }
        return resp;
    }
}
